package com.zou.lotterylucky.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.elvishew.xlog.XLog
import com.google.gson.Gson
import com.google.zxing.integration.android.IntentIntegrator
import com.jakewharton.rxbinding3.view.clicks
import com.kaopiz.kprogresshud.KProgressHUD
import com.qmuiteam.qmui.util.QMUIDirection
import com.qmuiteam.qmui.util.QMUIViewHelper
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.v2.request.RequestCenter
import com.v2.utils.TToast
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.LotteryApp
import com.zou.lotterylucky.R
import com.zou.lotterylucky.data.Order
import com.zou.lotterylucky.data.TimeLimit
import com.zou.lotterylucky.utils.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_keyboard.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import woyou.aidlservice.jiuiv5.ICallback
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.timerTask
import com.zou.lotterylucky.BuildConfig

class MainActivity : BaseActivity() {
    companion object {
        const val TAG = "MainActivity"
    }

    private var isModify = false
    private var todayCount: Int = 0
    lateinit var adapter: MyAdapter
    private lateinit var deal: Order
    private lateinit var timer: Timer
    private lateinit var requestQueue: RequestQueue
    private lateinit var lastClickBtn: View
    private var printing = false//是否正在打印中
//    private var seri_click = false


    override fun onBackPressed() {
        if (container_keyboard.visibility == View.GONE) {
            show_hide()
        } else if (isModify)
            super.onBackPressed()
    }

    lateinit var layoutManager: LinearLayoutManager

    private var isCopy = false

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 9 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //IntentIntegrator(this).initiateScan()
        } else {
            ToastUtil.showToast(this, "请手动开启摄像头权限")
            val localIntent = Intent()
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            localIntent.action = Intent.ACTION_VIEW;
            localIntent.setClassName(
                "com.android.settings",
                "com.android.settings.InstalledAppDetails"
            );
            localIntent.putExtra("com.android.settings.ApplicationPkgName", packageName);
            startActivity(localIntent)
        }
    }

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        WindowManager.LayoutParams.FLAG_SECURE//全屏

        lastClickBtn = View(this)
        requestQueue = Volley.newRequestQueue(this)
        isModify = intent.getBooleanExtra("Modify", false)

        if (!isModify) {
            topBar.addRightImageButton(R.drawable.ic_more_horiz_black_24dp, R.id.btn_menu)
                .clicks().subscribe { container_more.visibility = View.VISIBLE }

            var firstObj = JSONObject()
            firstObj.put("id", 0)
            firstObj.put("is_winner", 0)
            firstObj.put("is_paid", 0)
            firstObj.put("total_winning_amount", 0)
            firstObj.put("belong_to", "")
            firstObj.put("created_at", "")
            firstObj.put("serial_number", "")
            firstObj.put("is_deleted", 0)

            deal = Order(firstObj)

            val params = textDate.layoutParams as ConstraintLayout.LayoutParams
            params.marginStart = 4
            textDate.layoutParams = params
        } else {
            //topBar.addLeftBackImageButton().clicks().subscribe { onBackPressed() }
            deal = selectedOrder
            this.belongTo = mutableListOf()
        }

        RequestCenter.getServerTime(object : OkHttpRequestCallback {
            @SuppressLint("SetTextI18n")
            override fun onSuccess(response: String?) {
                textDate.text = JSONObject(response).getString("data").substring(8, 10) + "-" + JSONObject(response).getString("data").substring(5, 7) + "-" + JSONObject(response).getString("data").substring(0, 4)
            }

            override fun onFailure(error: String?) {
            }

        })
//        AidlUtil.instance.getTime("dd-MM-yyyy", object : TimeCallBack {
//            override fun onError(msg: String?) {
//
//            }
//
//            override fun onSuccess(time: String?) {
//                textDate.text = time
//            }
//        })

        logoutBtn.setOnClickListener {
            finish()
        }
        edtMoney.inputType = InputType.TYPE_NULL
        edtNum.inputType = InputType.TYPE_NULL
        edtMoney.setOnTouchListener { v, event ->
            edtMoney.requestFocus()
            false
        }

        edtNum.setOnTouchListener { v, event ->
            edtNum.requestFocus()
            false
        }

        edtMoney.clicks().subscribe {
            edtMoney.setText("")
        }
        edtNum.clicks().subscribe {
            edtNum.setText("")
        }

        edtMoney.requestFocus()

        container_more.clicks().subscribe { container_more.visibility = View.GONE }

        btn1.clicks().subscribe {
            edtMoney.append("1")
        }

        btnShow.clicks().subscribe {
            show_hide()
        }
        btnAdd.setOnClickListener {
            if (lastClickBtn == it && adapter.data.size > 0 && edtNum.text.toString().isEmpty()) {
                val num = adapter.data.first().getNumber().replace("P", "").trim()
                if (num.count() > 2) {
                    edtNum.setText(num.substring(1))
                }
            }
            lastClickBtn = it
            add(false)
        }
        btn_change.setOnClickListener {
            val builder = QMUIDialog.EditTextDialogBuilder(this)
            builder.setTitle("一键修改")
                .setInputType(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL)
                .addAction(R.string.cancel) { dialog, _ -> dialog.dismiss() }
                .addAction(R.string.confirm) { dialog, _ ->
                    var text = builder.editText.text.toString()
                    if (text != null && text.isNotEmpty()) {
                        var result = text.toDouble()
                        when {
                            (text.contains(".") && text.subSequence(text.indexOf(".") + 1, text.length).length > 2) -> {
                                Toast.makeText(this, "小数点后最多为2位", Toast.LENGTH_SHORT).show()
                            }
                            result == 0.0 -> {
                                Toast.makeText(this, "金额不能为0", Toast.LENGTH_SHORT).show()
                            }
                            result > 200 -> {
                                Toast.makeText(this, "金额不能大于200", Toast.LENGTH_SHORT).show()
                            }
                            text.split(".").size > 2 -> {
                                Toast.makeText(this, "金额不能包含多个小数点", Toast.LENGTH_SHORT).show()
                            }
                            ".".equals(text.first()) -> {
                                Toast.makeText(this, "金额错误", Toast.LENGTH_SHORT).show()
                            }
                            result.toFloat() % 0.25f != 0f -> {
                                Toast.makeText(this, getString(R.string.beishu), Toast.LENGTH_SHORT).show()
                            }
                            else -> {
                                for (betCountEntity in adapter.data) {
                                    betCountEntity.money = text.toDouble()
                                }
                                showCount()
                                adapter.notifyDataSetChanged()
                                dialog.dismiss()
                            }
                        }
                    } else {
                        Toast.makeText(this, "金额不能为空", Toast.LENGTH_SHORT).show()
                    }
                }
                .create().show()
        }
        btnAdd2.setOnClickListener {
            if (lastClickBtn == it && adapter.data.size > 0 && edtNum.text.toString().isEmpty()) {
                val num = adapter.data.first().getNumber().replace("P", "").trim()
                if (num.count() > 2) {
                    edtNum.setText(num.substring(1))
                }
            }
            lastClickBtn = it
            add(false)
        }

        btnPool.setOnClickListener {
            if (lastClickBtn == it && adapter.data.size > 0 && edtNum.text.toString().isEmpty()) {
                val num = adapter.data.first().getNumber().replace("P", "").trim()
                if (num.count() > 2) {
                    edtNum.setText(num.substring(1))
                }
            }
            lastClickBtn = it
            add(true)
        }

        btnNPool.setOnClickListener {
            if (lastClickBtn == it && adapter.data.size > 0 && edtNum.text.toString().isEmpty()) {
                val num = adapter.data.first().getNumber().replace("P", "").trim()
                if (num.count() > 2) {
                    edtNum.setText(num.substring(1))
                }
            }

            lastClickBtn = it
            val tempNum = edtNum.text.toString()
            add(false)
            edtNum.setText(tempNum)
            add(true)
        }

        btnBackspace.setOnClickListener {
            if (edtMoney.hasFocus()) {
                if (edtMoney.text.toString() != "") {
                    edtMoney.text.delete(edtMoney.text.length - 1, edtMoney.text.length)
                }
            } else {
                if (edtNum.text.toString() != "") {
                    edtNum.text.delete(edtNum.text.length - 1, edtNum.text.length)
                }
            }
        }
        btnTotal.setOnClickListener {
            startActivity(Intent(this, TotalActivity::class.java))
            container_more.visibility = View.GONE
        }
        btnCheck.setOnClickListener {
            startActivity(Intent(this, OrderListActivity::class.java))
            container_more.visibility = View.GONE
        }
        btnRedeem.setOnClickListener {
            startActivity(Intent(this, RedeemActivity::class.java))
            container_more.visibility = View.GONE
        }

        btnWinning.setOnClickListener {
            startActivity(Intent(this, WinLotteryActivity::class.java))
            container_more.visibility = View.GONE
        }
        btnOuter.setOnClickListener {
            startActivityForResult(Intent(this, SettingOuterActivity::class.java), 1)
            container_more.visibility = View.GONE
        }
        btnInsider.setOnClickListener {
            toSetting(true)
            container_more.visibility = View.GONE
        }

        btn0.clicks().subscribe { input("0") }
        btn1.clicks().subscribe { input("1") }
        btn2.clicks().subscribe { input("2") }
        btn3.clicks().subscribe { input("3") }
        btn4.clicks().subscribe { input("4") }
        btn5.clicks().subscribe { input("5") }
        btn6.clicks().subscribe { input("6") }
        btn7.clicks().subscribe { input("7") }
        btn8.clicks().subscribe { input("8") }
        btn9.clicks().subscribe { input("9") }
        btnDot.clicks().subscribe { input(".") }

        rbK.clicks().subscribe {
            if (this.belongTo.contains(0)) {
                this.belongTo.remove(0)
                rbK.setBackgroundColor(Color.parseColor("#3944BC"))
            } else if (timeLimits[0].isEnable()) {
                if (!checkRegionsLimit("K")) return@subscribe
                this.belongTo.add(0)
                rbK.setBackgroundColor(Color.parseColor("#99CC00"))
            }
            changeZone()
        }

        rbF.clicks().subscribe {
            if (this.belongTo.contains(1)) {
                this.belongTo.remove(1)
                rbF.setBackgroundColor(Color.parseColor("#3944BC"))
            } else if (timeLimits[1].isEnable()) {
                if (!checkRegionsLimit("F")) return@subscribe
                this.belongTo.add(1)
                rbF.setBackgroundColor(Color.parseColor("#99CC00"))
            }
            changeZone()
        }

        rbD.clicks().subscribe {
            if (this.belongTo.contains(2)) {
                this.belongTo.remove(2)
                rbD.setBackgroundColor(Color.parseColor("#3944BC"))
            } else if (timeLimits[2].isEnable()) {
                if (!checkRegionsLimit("D")) return@subscribe
                this.belongTo.add(2)
                rbD.setBackgroundColor(Color.parseColor("#99CC00"))
            }
            changeZone()
        }

        rbST.clicks().subscribe {
            if (this.belongTo.contains(3)) {
                this.belongTo.remove(3)
                rbST.setBackgroundColor(Color.parseColor("#3944BC"))
            } else if (timeLimits[3].isEnable()) {
                if (!checkRegionsLimit("T")) return@subscribe

                this.belongTo.add(3)
                rbST.setBackgroundColor(Color.parseColor("#99CC00"))
            }
            changeZone()
        }

        btn25.clicks().subscribe {
            input("0.25")
        }
        btn50.clicks().subscribe {
            input("0.5")
        }
        btn75.clicks().subscribe {
            input("Seri")
        }
        btnSwap.clicks().subscribe {
            if (edtMoney.hasFocus()) {
                edtNum.requestFocus()
            } else {
                edtMoney.requestFocus()
            }
        }

        btnScan.clicks()
            .throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                if (isModify) return@subscribe
                val permission = checkSelfPermission(Manifest.permission.CAMERA)
                if (permission == PackageManager.PERMISSION_GRANTED) {
                    IntentIntegrator(this)
                        .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE).initiateScan()
                } else {
                    requestPermissions(arrayOf(Manifest.permission.CAMERA), 9)
                }
            }

        layoutManager = LinearLayoutManager(this)
        rcv.layoutManager = layoutManager
        adapter = if (!isModify) MyAdapter(mutableListOf()) else MyAdapter(deal.bets)
        rcv.adapter = adapter

        adapter.setOnItemChildClickListener { _, view, position ->
            if (isCopy) return@setOnItemChildClickListener
            if (view.id == R.id.btnRemove) {
                adapter.remove(position)
            }
//            else if (view.id == R.id.textMoney) {
//                val builder = QMUIDialog.EditTextDialogBuilder(this)
//                builder.setTitle("修改金额")
//                        .setInputType(InputType.TYPE_CLASS_NUMBER)
//                        .addAction(R.string.cancel) { dialog, _ -> dialog.dismiss() }
//                        .addAction(R.string.confirm) { dialog, _ ->
//                            var text = builder.editText.text.toString()
//                            if (text != null && text.isNotEmpty()) {
//                                var result = text.toDouble()
//                                when {
//                                    result == 0.0 -> {
//                                        Toast.makeText(this, "金额不能为0", Toast.LENGTH_SHORT).show()
//                                    }
//                                    result > 200 -> {
//                                        Toast.makeText(this, "金额不能大于200", Toast.LENGTH_SHORT).show()
//                                    }
//                                    text.split(".").size > 2 -> {
//                                        Toast.makeText(this, "金额不能包含多个小数点", Toast.LENGTH_SHORT).show()
//                                    }
//                                    ".".equals(text.first()) -> {
//                                        Toast.makeText(this, "金额错误", Toast.LENGTH_SHORT).show()
//                                    }
//                                    result.toFloat() % 0.25f != 0f -> {
//                                        Toast.makeText(this, getString(R.string.beishu), Toast.LENGTH_SHORT).show()
//                                    }
//                                    else -> {
//                                        val betCountEntity = adapter.data[position]
//                                        betCountEntity.money = text.toDouble()
//                                        adapter.notifyItemChanged(position)
//                                        dialog.dismiss()
//                                    }
//                                }
//                            } else {
//                                Toast.makeText(this, "金额不能为空", Toast.LENGTH_SHORT).show()
//                            }
//                        }
//                        .create().show()
//            }
//            else if (view.id == R.id.textNum){
//                val builder = QMUIDialog.EditTextDialogBuilder(this)
//                builder.setTitle("修改号码")
//                        .setInputType(InputType.TYPE_CLASS_NUMBER)
//                        .addAction(R.string.cancel) { dialog, _ -> dialog.dismiss() }
//                        .addAction(R.string.confirm) { dialog, _ ->
//                            var text = builder.editText.text.toString()
//                            if (text != null && text.isNotEmpty()) {
//                                var text_int = text.toInt()
//                                when {
//                                    text.contains('.') -> {
//                                        Toast.makeText(this, "号码错误", Toast.LENGTH_SHORT).show()
//                                    }
//                                    text_int > 9999 -> {
//                                        Toast.makeText(this, "号码不能超过9999", Toast.LENGTH_SHORT).show()
//                                    }
//                                    else -> {
//                                        val betCountEntity = adapter.data[position]
//                                        betCountEntity.num = text_int
//                                        adapter.notifyItemChanged(position)
//                                        dialog.dismiss()
//                                    }
//                                }
//
//                            }else{
//                                Toast.makeText(this, "号码不能为空", Toast.LENGTH_SHORT).show()
//                            }
//                        }
//                        .create().show()
//            }
            showCount()
        }

        if (isModify) {
            if (deal.belongTo.contains("K")) {
                if (timeLimits[0].isEnable()) {
                    this.belongTo.add(0)
                    rbK.setBackgroundColor(Color.parseColor("#99CC00"))
                }
            }

            if (deal.belongTo.contains("F")) {
                if (timeLimits[1].isEnable()) {
                    this.belongTo.add(1)
                    rbF.setBackgroundColor(Color.parseColor("#99CC00"))
                }
            }

            if (deal.belongTo.contains("D")) {
                if (timeLimits[2].isEnable()) {
                    this.belongTo.add(2)
                    rbD.setBackgroundColor(Color.parseColor("#99CC00"))
                }
            }

            if (deal.belongTo.contains("S")) {
                if (timeLimits[3].isEnable()) {
                    this.belongTo.add(3)
                    rbST.setBackgroundColor(Color.parseColor("#99CC00"))
                }
            }
        }

        printing = false
        btnPrint.setOnClickListener {
            if (belongTo.size == 0) {
                ToastUtil.showMsg(this, R.string.select_region)
                return@setOnClickListener
            }

            if (adapter.data.isEmpty()) return@setOnClickListener

            if (printing) return@setOnClickListener

            if (!isTimeLimit(deal.belongTo)) {
                return@setOnClickListener
            }

            if (!isNetworkAvailable(this)) {
                ToastUtil.showToast(this, getString(R.string.internet_fail))
                return@setOnClickListener
            }

            if (Constants.OPEN_PRINT) {
                if (!AidlUtil.instance.isConnect && !BuildConfig.DEBUG) {
                    ToastUtil.showToast(this, getString(R.string.weilianjiadayinfuwu))
                    printing = false
                    return@setOnClickListener
                }
            }

            if (adapter.data.isEmpty()) {
                ToastUtil.showToast(this, getString(R.string.weitianjiahaoma))
                printing = false
                return@setOnClickListener
            }

            deal.bets = mutableListOf()
            deal.bets.addAll(adapter.data)

            loadTodayOrders()

//            val timeNowStamp = AidlUtil.instance.getTimeStampNow()
//            if (timeNowStamp > 0L) {
//                deal.serialNumber = LotteryApp.getXuhao(
//                    this@MainActivity,
//                    timeNowStamp,
//                    todayCount + 1
//                )
//                saveDeal(deal)
//            } else {
//                ToastUtil.showMsg(this, "时间同步未完成，请稍后再试")
//            }
        }
        showCount()
        checkPermission()
        allOrders = mutableListOf()
        deletedOrders = mutableListOf()
        todayOrders = mutableListOf()
        todayBets = mutableListOf()
    }

    private fun setupRegin() {
        if (deal.belongTo.contains("K")) {
            if (timeLimits[0].isEnable()) {
                this.belongTo.add(0)
            }
        }

        if (deal.belongTo.contains("F")) {
            if (timeLimits[1].isEnable()) {
                this.belongTo.add(1)
            }
        }

        if (deal.belongTo.contains("D")) {
            if (timeLimits[2].isEnable()) {
                this.belongTo.add(2)
            }
        }

        if (deal.belongTo.contains("S")) {
            if (timeLimits[3].isEnable()) {
                this.belongTo.add(3)
            }
        }
    }

    private fun checkPermission() {
        val permission = checkSelfPermission(Manifest.permission.CAMERA)
        if (permission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.CAMERA), 9)
        }
    }

    private fun add(isPool: Boolean) {
        if (belongTo.size == 0) {
            ToastUtil.showMsg(this, R.string.select_region)
            return
        }

        var strMoney = edtMoney.text.toString()
        if (strMoney.isEmpty() || strMoney == "0") {
            showWarn(getString(R.string.qsrje))
            return
        }
        if (strMoney.endsWith(".")) strMoney += "0"
        val money = strMoney.toFloatOrNull()
        if (money == null) {
            showWarn(getString(R.string.jinecw))
            return
        } else {
            if (money % 0.25f != 0f) {
                showWarn(getString(R.string.beishu))
                return
            }
        }

        val strNumber = edtNum.text.toString()

        if (strNumber.isEmpty()) {
            showWarn(getString(R.string.shuruhaoma))
            return
        }

        if (strNumber.length == 1) {
            showWarn(getString(R.string.two_digits))
            return
        }

        val type = when (strNumber.length) {
            3 -> 3
            4 -> 4
            else -> 2
        }

        if (strNumber.contains("*")) {
//            都转化为4位数统一处理
            val temp_str = when (strNumber.length) {
                2 -> "0" + "0" + strNumber
                3 -> "0" + strNumber
                else -> strNumber
            }
            val index = temp_str.indexOf("*")
            var j = 0
            for (i in 0..9) {
                var subNumber = when (index) {
                    0 -> i * 1000 + temp_str.substring(1).toInt() //*---
                    1 -> temp_str.substring(0, 1).toInt() * 1000 + i * 100 + temp_str.substring(2).toInt() //-*--
                    2 -> temp_str.substring(0, 2).toInt() * 100 + i * 10 + temp_str.substring(3).toInt() //--*-
                    3 -> temp_str.substring(0, 3).toInt() * 10 + i // ---*
                    else -> 0
                }
                if (subNumber != 0) {
                    val bet = BetCountEntity()
                    bet.num = subNumber
                    bet.money = money.toDouble()
                    bet.type = type
                    bet.pool = isPool
                    adapter.addData(j, bet)
                    j++
                } else {
                    if (j == 0) j = 0
                    else j--
                }
            }
        } else {
            val number = strNumber.toInt()
            val bet = BetCountEntity()
            bet.num = number
            bet.money = money.toDouble()
            bet.type = type
            bet.pool = isPool
            adapter.addData(0, bet)
        }
        layoutManager.scrollToPosition(0)

        textPool.visibility = View.GONE
        edtNum.setText("")
        showCount()
        justAdded = true
//        seri_click = false
//       test 07-10
//        loadTodayAllBets()
    }

    private fun checkSeriIndex(length: Int, strNumber: String) {
//        ----
        val index = strNumber.indexOf("*")

    }

    private fun checkRegionsLimit(regionStr: String): Boolean {
        for (bet in adapter.data) {
            if (!findLimit(bet, true, regionStr)) {
                return false
            }
        }

        return true
    }

    private fun findLimit(bet: BetCountEntity, checkRegion: Boolean, region: String): Boolean {

//        test 07-10

//        var find: List<BetCountEntity> = mutableListOf()
//        var sum = 0.0
//        var limit = 0
//
//        val regions = arrayOf("K", "F", "D", "S")
//        for (i in regions) {
//            if (region.contains(i)) {
//                find = todayBets.filter {
//                    it.type == bet.type && it.num == bet.num && it.belongTo.contains(i) && it.pool == bet.pool
//                }
//
//                sum = find.sumByDouble { it.money } + adapter.data.filter {
//                    it.num == bet.num && it.type == bet.type && it.pool == bet.pool
//                }.sumByDouble { it.money }
//
//                limit = getLimit(this, i, bet.getNumber(), bet.type, bet.pool)
//
//                if (sum > limit) {
//                    //showWarn(LotteryApp.getTitleSimple(i) + getString(R.string.shengyu) + (limit.toDouble() - find.sumByDouble { it.money }))
//                    showWarn(LotteryApp.getTitleSimple(i) + bet.num.toString() + getString(R.string.shengyu) + (limit.toDouble() - find.sumByDouble { it.money }))
//                    return false
//                }
//            }
//        }

        return true
    }

    private fun findLimit(bet: BetCountEntity, checkRegion: Boolean): Boolean {
//        test 07-10
//        var find: List<BetCountEntity> = mutableListOf()
//        var sum = 0.0
//        var limit = 0
//
//        val regions = arrayOf("K", "F", "D", "S")
//        for (i in regions) {
//            if (deal.belongTo.contains(i)) {
//                find = todayBets.filter {
//                    it.type == bet.type && it.num == bet.num && it.belongTo.contains(i) && it.pool == bet.pool
//                }
//
//                sum = when {
//                    !checkRegion -> {
//                        find.sumByDouble { it.money } + adapter.data.filter {
//                            it.num == bet.num && it.type == bet.type && it.pool == bet.pool
//                        }.sumByDouble { it.money }
//                    }
//                    else -> {
//                        find.sumByDouble { it.money }
//                    }
//                }
//
//                limit = getLimit(this, i, bet.getNumber(), bet.type, bet.pool)
//
//                if ((sum + bet.money) > limit) {
//                    // showWarn(LotteryApp.getTitleSimple(i) + getString(R.string.shengyu) + (limit.toDouble() - sum))
//                    showWarn(
//                        LotteryApp.getTitleSimple(i) + "    " + bet.num.toString() + getString(
//                            R.string.shengyu
//                        ) + (limit.toDouble() - sum)
//                    )
//                    return false
//                }
//            }
//        }

        return true
    }

    private fun getLimit(
        context: Context,
        belong: String,
        betNumber: String,
        type: Int,
        isPool: Boolean
    ): Int {
        if (isPool) {
            if (belong.contains("K")) {
                val specialNumberLimit = moneyLimits[0].numberLimits.find { it ->
                    it.number.toUpperCase().replace("P", "").trim()
                        .toInt() == betNumber.replace("P", "").trim().toInt()
                }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[0].fPoolLimit
                        3 -> return moneyLimits[0].tPoolLimit
                        2 -> return moneyLimits[0].sPoolLimit
                    }
                }
            }

            if (belong.contains("F")) {
                val specialNumberLimit = moneyLimits[1].numberLimits.find { it ->
                    it.number.toUpperCase().replace("P", "").trim()
                        .toInt() == betNumber.replace("P", "").trim().toInt()
                }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[1].fPoolLimit
                        3 -> return moneyLimits[1].tPoolLimit
                        2 -> return moneyLimits[1].sPoolLimit
                    }
                }
            }

            if (belong.contains("D")) {
                val specialNumberLimit = moneyLimits[2].numberLimits.find { it ->
                    it.number.toUpperCase().replace("P", "").trim()
                        .toInt() == betNumber.replace("P", "").trim().toInt()
                }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[2].fPoolLimit
                        3 -> return moneyLimits[2].tPoolLimit
                        2 -> return moneyLimits[2].sPoolLimit
                    }
                }
            }

            if (belong.contains("S")) {
                val specialNumberLimit = moneyLimits[3].numberLimits.find { it ->
                    it.number.toUpperCase().replace("P", "").trim()
                        .toInt() == betNumber.replace("P", "").trim().toInt()
                }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[3].fPoolLimit
                        3 -> return moneyLimits[3].tPoolLimit
                        2 -> return moneyLimits[3].sPoolLimit
                    }
                }
            }
        } else {
            if (belong.contains("K")) {
                val specialNumberLimit =
                    moneyLimits[0].numberLimits.find { it -> it.number == betNumber }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[0].fLimit
                        3 -> return moneyLimits[0].tLimit
                        2 -> return moneyLimits[0].sLimit
                    }
                }
            }

            if (belong.contains("F")) {
                val specialNumberLimit =
                    moneyLimits[1].numberLimits.find { it -> it.number == betNumber }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[1].fLimit
                        3 -> return moneyLimits[1].tLimit
                        2 -> return moneyLimits[1].sLimit
                    }
                }
            }

            if (belong.contains("D")) {
                val specialNumberLimit =
                    moneyLimits[2].numberLimits.find { it -> it.number == betNumber }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[2].fLimit
                        3 -> return moneyLimits[2].tLimit
                        2 -> return moneyLimits[2].sLimit
                    }
                }
            }

            if (belong.contains("S")) {
                val specialNumberLimit =
                    moneyLimits[3].numberLimits.find { it -> it.number == betNumber }
                if (specialNumberLimit != null) {
                    return specialNumberLimit.limit
                } else {
                    when (type) {
                        4 -> return moneyLimits[3].fLimit
                        3 -> return moneyLimits[3].tLimit
                        2 -> return moneyLimits[3].sLimit
                    }
                }
            }
        }

        return 0
    }

    @SuppressLint("SetTextI18n")
    private fun showCount() {
        textBetsCount.text = getString(R.string.dingdanshu_dot) + adapter.data.size * belongTo.size
        textMoneyCount.text =
            getString(R.string.jine_dot) + adapter.data.sumByDouble { it.money * belongTo.size }
    }

    // 重选区域
    private fun changeZone() {
        var region = ""

        if (belongTo.contains(0)) {
            region = "K"
        }

        if (belongTo.contains(1)) {
            if (region.isNotEmpty()) {
                region += "+F"
            } else {
                region = "F"
            }
        }

        if (belongTo.contains(2)) {
            if (region.isNotEmpty()) {
                region += "+D"
            } else {
                region = "D"
            }
        }

        if (belongTo.contains(3)) {
            if (region.isNotEmpty()) {
                region += "+S"
            } else {
                region = "S"
            }
        }

        deal.belongTo = region
        for (bet in adapter.data) {
            bet.belongTo = region
        }

        adapter.notifyDataSetChanged()
    }


    private fun showWarn(s: String) {
        QMUIDialog.MessageDialogBuilder(this)
            .setMessage(s)
            .addAction("OK") { a, b ->
                a.dismiss()
            }.setCancelable(false)
            .create().show()
    }

    private fun show_hide() {
        if (container_keyboard.visibility == View.VISIBLE) {
            QMUIViewHelper.slideOut(
                container_keyboard,
                400,
                null,
                true,
                QMUIDirection.TOP_TO_BOTTOM
            )
            container_keyboard.visibility = View.GONE

            val param = rcv.layoutParams as ConstraintLayout.LayoutParams
            param.topToBottom = R.id.topBar
            rcv.layoutParams = param
        } else {
            QMUIViewHelper.slideIn(
                container_keyboard,
                400,
                null,
                true,
                QMUIDirection.BOTTOM_TO_TOP
            )

            val param = rcv.layoutParams as ConstraintLayout.LayoutParams
            param.topToBottom = R.id.edtMoney
            rcv.layoutParams = param
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)

        if (result != null) {
            val str = result.contents
            XLog.e(str)
            try {
                val jsonBean = JSONObject(str)
                val number = jsonBean.getString("or")
                val machineNumber = SPUtils[this, "username", "0001"] as String
                val jihao = number.substring(0, machineNumber.length)

                if (jihao != machineNumber) {
                    ToastUtil.showMsg(this, "机号不符")
                    return
                }
                loadOrderByNumber(number)

//                selectedOrder = allOrders.find { it -> it.serialNumber == number }!!
//                if (selectedOrder != null) {
//                    val intent = Intent(this, OrderDetailActivity::class.java)
//                    startActivity(intent)
//                } else {
//                    ToastUtil.showTipsNotFound(this)
//                }
            } catch (e: Exception) {
                XLog.e(e)
                ToastUtil.showTipsError(this, getString(R.string.error_qr))
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
            if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
                val intent =
                    Intent(
                        this@MainActivity,
                        MainActivity::class.java
                    )
                startActivity(intent)
                finish()
            }
        }
    }

    private fun toSetting(isInner: Boolean) {
        val builder = QMUIDialog.EditTextDialogBuilder(this)
        builder.setTitle(getString(R.string.shezhi))
            .setPlaceholder(getString(R.string.qingshurumima))
            .setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            .addAction(R.string.cancel) { dialog, _ -> dialog.dismiss() }
            .addAction(R.string.confirm) { dialog, _ ->
                val text = builder.editText.text
                if (text != null && text.isNotEmpty()) {
                    //                                Toast.makeText(this, "您的昵称: $text", Toast.LENGTH_SHORT).show()
                    val psd =
                        SPUtils.get(
                            this,
                            "password",
                            Constants.default_psd
                        ) as String
                    TLog.v("合计校验密码${text.toString()}, SP:${psd}")
                    if (text.toString() == psd) {
                        if (isInner) {
                            startActivityForResult(
                                Intent(this, SettingInnerActivity::class.java),
                                1
                            )
                        } else {
                            startActivityForResult(
                                Intent(this, SettingOuterActivity::class.java),
                                1
                            )
                        }

                        dialog.dismiss()
                    } else {
                        Toast.makeText(this, getString(R.string.password_error), Toast.LENGTH_SHORT)
                            .show()
                    }

                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.please_input_password),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
            .create().show()
    }

    private var justAdded = false

    private fun input(s: String) {
        if (edtMoney.hasFocus()) {
            if (s == "Seri") return
            if (justAdded) {
                edtMoney.setText("")
                justAdded = false
            }
            val current = edtMoney.text.toString()
            if (current.isEmpty() && s == ".") return
            if (current.contains(".") && s == ".") return
            if (current == "0" && s == "0") return
            if (current.length > 8) return

            if (s == "0.25" || s == "0.5") {
                edtMoney.setText(s)
            } else {
                val ns = current + s
                var result = ns.toDouble()
                if (ns.contains(".")) {
                    var index = ns.indexOf(".")
                    if (ns.length - index > 3) {
                        return
                    }
                }
                if (result > 200) return
                edtMoney.setText(current + s)
            }


        } else {
            if (s.contains(".")) return
            var current = edtNum.text.toString()
//            if (current == "0" && s == "0") return
            if (current.contains("*") && s == "Seri") return
            if (s == "Seri") {
//                seri_click = true
                current += "*"
            } else {
                current += s
            }
//            val ns = current + s

//            var i = ns.toInt()
//            if (i > 9999) return
            if (current.length > 4) return
            edtNum.setText(current)
        }
    }

    private fun serverPing() {
        timer = Timer()
        timer.scheduleAtFixedRate(timerTask {
            GlobalScope.async {
                RequestCenter.getServerTime(object : OkHttpRequestCallback {
                    @SuppressLint("SetTextI18n")
                    override fun onSuccess(response: String?) {
                        textDate.text = JSONObject(response).getString("data").substring(8, 10) + "-" + JSONObject(response).getString("data").substring(5, 7) + "-" + JSONObject(response).getString("data").substring(0, 4)
                    }

                    override fun onFailure(error: String?) {
                    }

                })

//                AidlUtil.instance.getTime("dd-MM-yyyy", object : TimeCallBack {
//                    override fun onError(msg: String?) {
//
//                    }
//
//                    override fun onSuccess(time: String?) {
//                        textDate.text = time
//                    }
//                })

//                val url = Constants.SERVER_URL + "ping"
//                val params = JSONObject()
//                val time = textDate.text
//                params.put("machine_number", SPUtils[this@MainActivity, "username", ""])
//                params.put("password", SPUtils[this@MainActivity, "password", ""])
//                params.put("time", time)

                //
                RequestCenter.appPing(SPUtils["username", ""] as String, SPUtils["password", ""] as String, object : OkHttpRequestCallback {
                    override fun onSuccess(result: String?) {
                        TLog.net("appPing success, result:${result}")
                        var response = JSONObject(result)
                        response = response.getJSONObject("data")
                        if (response.getInt("isLogin") != 1) {
                            TToast.show("退出登录")
                            finish()
                            return
                        }
                        if (response.getInt("isRegionSuccess") != 1) {
                            TToast.show("地区数据错误，请联系管理员！")
                            return
                        }
                        val defaultJson = "{\"start\":\"\", \"end\":\"\",\"disable\":0}"
                        timeLimits = mutableListOf()
                        val timeLimit1 = TimeLimit(JSONObject(defaultJson))
                        timeLimit1.enable = response.getBoolean("regionKEnable")
                        timeLimits.add(timeLimit1)
                        val timeLimit2 = TimeLimit(JSONObject(defaultJson))
                        timeLimit2.enable = response.getBoolean("regionFEnable")
                        timeLimits.add(timeLimit2)
                        val timeLimit3 = TimeLimit(JSONObject(defaultJson))
                        timeLimit3.enable = response.getBoolean("regionDEnable")
                        timeLimits.add(timeLimit3)
                        val timeLimit4 = TimeLimit(JSONObject(defaultJson))
                        timeLimit4.enable = response.getBoolean("regionSEnable")
                        timeLimits.add(timeLimit4)
                        displayRegion()
                    }

                    override fun onFailure(error: String?) {
                        TLog.net("appPing failure:$error")
                    }
                })
                //

//                val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//                    try {
//                        val status = response.get("status") as Int
//                        val msg = response.get("message").toString()
//                        if (status == 200 && !response.isNull("data")) {
//                            val data = response.get("data") as JSONObject
//                            val timeLimitsData = data.get("todayTimeLimit") as JSONArray
//                            timeLimits = mutableListOf()
//                            for (i in 0..3) {
//                                val timeLimit = TimeLimit(timeLimitsData.getJSONObject(i))
//                                timeLimits.add(timeLimit)
//                            }
//                            val moneyLimitsData = data.get("regions") as JSONArray
//                            moneyLimits = mutableListOf()
//                            for (i in 0..3) {
//                                val moneyLimit = MoneyLimit(moneyLimitsData.getJSONObject(i))
//                                val specialData =
//                                    moneyLimitsData.getJSONObject(i).getJSONArray("special_numbers")
//                                for (j in 0 until specialData.length()) {
//                                    val specialNumberLimit =
//                                        SpecialNumberLimit(specialData.getJSONObject(j))
//                                    moneyLimit.numberLimits.add(specialNumberLimit)
//                                }
//                                moneyLimits.add(moneyLimit)
//                            }
//                            displayRegion()
//                        }
//                        if (msg == "logout") {
//                            finish()
//                        }
//                    } catch (e: JSONException) {
//                        e.printStackTrace()
//                    }
//                }, { error -> error.printStackTrace() })
//                requestQueue?.add(request)
            }
        }, 0, 5000)
    }

    private fun displayRegion() {
        val colorSelected = getColor(R.color.area_selected)//选中时的颜色
        val colorUnselected = getColor(R.color.area_unselected)//没有被选中时的颜色
        val colorForbid = getColor(R.color.area_forbid)//被禁用时的颜色

        if (timeLimits[0].enable!!) {
            rbK.setBackgroundColor(colorUnselected)
            if (deal.belongTo.contains("K")) {
                rbK.setBackgroundColor(colorSelected)
            }
        } else {
            rbK.setBackgroundColor(colorForbid)
        }
        if (timeLimits[1].enable!!) {
            rbF.setBackgroundColor(colorUnselected)
            if (deal.belongTo.contains("F")) {
                rbF.setBackgroundColor(colorSelected)
            }
        } else {
            rbF.setBackgroundColor(colorForbid)
        }
        if (timeLimits[2].enable!!) {
            rbD.setBackgroundColor(colorUnselected)
            if (deal.belongTo.contains("D")) {
                rbD.setBackgroundColor(colorSelected)
            }
        } else {
            rbD.setBackgroundColor(colorForbid)
        }
        if (timeLimits[3].enable!!) {
            rbST.setBackgroundColor(colorUnselected)
            if (deal.belongTo.contains("S")) {
                rbST.setBackgroundColor(colorSelected)
            }
        } else {
            rbST.setBackgroundColor(colorForbid)
        }
    }

    private fun loadOrders() {
        val url = Constants.SERVER_URL + "getOrders"
        val params = JSONObject()
        params.put("machine_number", SPUtils[this, "username", ""])
        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()
        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
            try {
                val status = response.get("status") as Int
                if (status == 200 && !response.isNull("data")) {
                    hud.dismiss()
                    val data = response.get("data") as JSONArray
                    allOrders = mutableListOf()
                    deletedOrders = mutableListOf()
                    todayOrders = mutableListOf()
                    for (i in 0 until data.length()) {
                        val order = Order(data.getJSONObject(i))
                        val orderBets = mutableListOf<BetCountEntity>()
                        val betsData = data.getJSONObject(i).getJSONArray("bet_numbers")
                        for (j in 0 until betsData.length()) {
                            val bet = BetCountEntity()
                            val betData = betsData.getJSONObject(j)
                            bet.num =
                                betData.getString("bet_number").replace("P", "").trim().toInt()
                            bet.money = betData.getDouble("bet_money")
                            bet.pool = betData.getInt("is_pool") == 1
                            bet.type =
                                betData.getString("bet_number").replace("P", "").trim().length
                            bet.belongTo = data.getJSONObject(i).getString("belong_to")
                            bet.isWinner = betData.getInt("is_winner")
                            bet.rank = betData.getInt("rank")
                            bet.prizes = betData.getDouble("prizes")
                            orderBets.add(bet)
                        }

                        order.bets.addAll(orderBets)

                        if (order.isDeleted == 0) {
                            allOrders.add(order)
                            if (ClockUtil.isToday(order.timeStrAuto)) {
                                todayOrders.add(order)
                            }
                        } else {
                            if (ClockUtil.isToday(order.timeStrAuto)) {
                                deletedOrders.add(order)
                            }
                        }
                    }
//                    test 07-10
//                    loadTodayAllBets()
                }
            } catch (e: JSONException) {
                hud.dismiss()
                e.printStackTrace()
            }
        }, { error ->
            hud.dismiss()
            error.printStackTrace()
        })

        requestQueue.add(request)
    }


    private fun loadTodayOrders() {
//        val url = Constants.SERVER_URL + "getTodayOrders"
//        val params = JSONObject()
        var today = ""
//        params.put("machine_number", SPUtils[this, "username", ""])
//        val dateFormatter = SimpleDateFormat("yyyy-MM-dd")
//        var reqTime = ""
        RequestCenter.getServerTime(object : OkHttpRequestCallback {
            override fun onSuccess(response: String?) {
                val time = JSONObject(response).getString("data").substring(0, 10)
//                params.put("date", time)
//                reqTime = SimpleDateFormat("yyyy-MM-dd").format(Date())
                today = time.replace("-", "", ignoreCase = true)
            }

            override fun onFailure(error: String?) {
            }

        })
//        AidlUtil.instance.getTime("yyyy-MM-dd", object : TimeCallBack {
//            override fun onError(msg: String?) {
//            }
//
//            override fun onSuccess(time: String?) {
//                params.put("date", time)
//                reqTime = SimpleDateFormat("yyyy-MM-dd").format(Date())
//                today = time!!.replace("-", "", ignoreCase = true)
//            }
//        })
        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()


        RequestCenter.getSerialNumber(object : OkHttpRequestCallback {
            override fun onSuccess(response: String?) {
                hud.dismiss()
                deal.serialNumber = LotteryApp.getXuhao(
                    this@MainActivity,
                    today,
                    JSONObject(response).getInt("data")
                )

                saveDeal(deal)
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TLog.net("appGetOrders failure:$error")
            }
        })
//        RequestCenter.appGetOrders(SPUtils["username", ""] as String, "", "", reqTime, reqTime, object : OkHttpRequestCallback {
//            override fun onSuccess(response: String?) {
//                hud.dismiss()
//                //查询订单后生成serialNumber
//
//
////                deal.serialNumber = LotteryApp.getXuhao(
////                        this@MainActivity,
////                        today, data + 1
////                    )
//
//            }
//
//            override fun onFailure(error: String?) {
//                hud.dismiss()
//                TLog.net("appGetOrders failure:$error")
//            }
//        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//                hud.dismiss()
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.get("data") as Int
//                    deal.serialNumber = LotteryApp.getXuhao(
//                        this@MainActivity,
//                        today,
//                        data + 1
//                    )
//                    saveDeal(deal)
//
//                }
//            } catch (e: JSONException) {
//                hud.dismiss()
//                e.printStackTrace()
//            }
//        }, { error ->
//            hud.dismiss()
//            error.printStackTrace()
//        })
//
//        requestQueue.add(request)
    }

    private fun loadOrderByNumber(number: String) {
//        val url = Constants.SERVER_URL + "getOrderBySerialNumber"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
//        params.put("serial_number", number)

        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()

        RequestCenter.appGetOrders(SPUtils["username", ""] as String, number, "", "", "", object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                try {
                    hud.dismiss()
                    if (JSONObject(result).getJSONArray("data").length() < 1) {
                        ToastUtil.showTipsNotFound(this@MainActivity)
                        return
                    }
                    val data = JSONObject(result).getJSONArray("data")[0] as JSONObject
                    val orderBets = mutableListOf<BetCountEntity>()
                    val betsData = data.getJSONArray("bet_numbers")
                    val order = Order(data)
                    adapter.data.clear()
                    for (j in 0 until betsData.length()) {
                        val bet = BetCountEntity()
                        val betData = betsData.getJSONObject(j)
                        bet.num =
                            betData.getString("bet_number").replace("P", "").trim().toInt()
                        bet.money = betData.getDouble("bet_money")
                        bet.pool = betData.getInt("is_pool") == 1
                        bet.type =
                            betData.getString("bet_number").replace("P", "").trim().length
                        bet.belongTo = data.getString("belong_to")
                        bet.isWinner = betData.getInt("is_winner")
                        bet.rank = betData.getInt("rank")
                        bet.prizes = betData.getDouble("prizes")
                        orderBets.add(bet)
//                        adapter.addData(0, bet)

                    }
                    order.bets.addAll(orderBets)
                    selectedOrder = order

                    if (selectedOrder != null) {
                        val intent = Intent(this@MainActivity, OrderDetailActivity::class.java)
                        startActivity(intent)
                    } else {
                        ToastUtil.showTipsNotFound(this@MainActivity)
                    }
                } catch (e: JSONException) {
                    hud.dismiss()
                    e.printStackTrace()
                }
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TLog.net("getOrders failure:$error")
            }
        })
//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//                hud.dismiss()
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.get("data") as JSONObject
//                    val orderBets = mutableListOf<BetCountEntity>()
//                    val betsData = data.getJSONArray("bet_numbers")
//                    val order = Order(data)
//                    adapter.data.clear()
//                    for (j in 0 until betsData.length()) {
//                        val bet = BetCountEntity()
//                        val betData = betsData.getJSONObject(j)
//                        bet.num =
//                            betData.getString("bet_number").replace("P", "").trim().toInt()
//                        bet.money = betData.getDouble("bet_money")
//                        bet.pool = betData.getInt("is_pool") == 1
//                        bet.type =
//                            betData.getString("bet_number").replace("P", "").trim().length
//                        bet.belongTo = data.getString("belong_to")
//                        bet.isWinner = betData.getInt("is_winner")
//                        bet.rank = betData.getInt("rank")
//                        bet.prizes = betData.getDouble("prizes")
//                        orderBets.add(bet)
////                        adapter.addData(0, bet)
//
//                    }
//                    order.bets.addAll(orderBets)
//                    selectedOrder = order
//
//                    if (selectedOrder != null) {
//                        val intent = Intent(this, OrderDetailActivity::class.java)
//                        startActivity(intent)
//                    } else {
//                        ToastUtil.showTipsNotFound(this)
//                    }
//
////                    if (selectedOrder != null) {
////                        allOrders = mutableListOf()
////                        deletedOrders = mutableListOf()
////                        todayOrders = mutableListOf()
////                        todayBets = mutableListOf()
////                        edtMoney.setText("")
////                        edtNum.setText("")
////                        val editBelongTo = editTimeLimit(order.belongTo)
////                        if (editBelongTo.isNotEmpty()) {
////                            selectedOrder.belongTo = editBelongTo
////                        }
////                        deal = selectedOrder
////                        this.belongTo = mutableListOf()
////                        displayRegion()
////                        setupRegin()
////                    } else {
////                        ToastUtil.showTipsNotFound(this)
////                    }
//                } else {
//                    ToastUtil.showTipsNotFound(this)
//                }
//            } catch (e: JSONException) {
//                hud.dismiss()
//                e.printStackTrace()
//            }
//        }, { error ->
//            hud.dismiss()
//            error.printStackTrace()
//        })
//
//        requestQueue.add(request)
    }

    private fun saveDeal(deal: Order) {
        deal.machine_number = SPUtils["username", ""] as String
        for (i in 0 until deal.bets.size) {
            deal.bets[i].srcNumber = deal.bets[i].getNumber()
        }

        TLog.v("enter saveDeal, deal:${Gson().toJson(deal)}")

//        val url = Constants.SERVER_URL + "saveOrder"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this@MainActivity, "username", ""])
//        params.put("belong_to", deal.belongTo)
//        params.put("serial_number", deal.serialNumber)
//
//        val betsList = JSONArray()
//        for (i in 0 until deal.bets.size) {
//            val bet = JSONObject()
//            bet.put("bet_number", deal.bets[i].getNumber())
//            bet.put("is_pool", deal.bets[i].pool)
//            bet.put("bet_money", deal.bets[i].money)
//            betsList.put(bet)
//        }
//
//        params.put("bets", betsList)


        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()

        RequestCenter.saveOrder(Gson().toJson(deal), object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                val obj = JSONObject(result)
                if (obj.has("code") && !obj.getString("code").equals("200")) {
                    showWarn(obj.getString("message"))
                    return
                }

                Log.d("jsonjson", "saveOrder result:" + result)
                TLog.net("saveOrder() success:$result")
                hud.dismiss()
                val data = JSONObject(result)
                when (data.getInt("status")) {
                    400 -> {
                        showWarn(data.getString("message"))
                    }
                    600 -> {
                        showWarn(data.getString("message"))
                        todayCount += 1
                    }
                    200 -> {
                        deal.id = data.getJSONObject("order").getInt("id")
                        deal.timeStrAuto = data.getJSONObject("order").getString("created_at")
                        TLog.net("saveOrder()<==deal:${Gson().toJson(deal)}")
                        if (Constants.OPEN_PRINT) {
                            printOrder()
                        }
                    }
                }
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                showWarn("error")
                TLog.net("saveOrder() failure:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params,
//            { response ->
//                hud.dismiss()
//                when (response.get("status") as Int) {
//
//                    200 -> {
//                        if (!response.isNull("data")) {
//                            val data = response.getJSONArray("data")
//                            val order = Order(data.getJSONObject(data.length() - 1))
//                            deal.id = order.id
//                            deal.timeStrAuto = order.timeStrAuto
//
//                        }
//                        printOrder()
//                    }
//                    400 -> {
//                        if (!response.isNull("data")) {
//                            val data = response.getJSONObject("data")
//                            val region = data.getString("region")
//                            val betNumber = data.getString("bet_number")
//                            val available = data.getDouble("available")
//                            showWarn(
//                                betNumber + " : " + LotteryApp.getTitleSimple(region) + getString(
//                                    R.string.shengyu
//                                ) + available
//                            )
//                        } else {
//                            val tip = response.getString("message")
//                            showWarn(tip)
//                        }
//                    }
//                    600 -> {
//                        val tip = response.getString("message")
//                        showWarn(tip)
//                        todayCount += 1
//                    }
//
//                }
//            },
//            { error ->
//                hud.dismiss()
//
//                showWarn("error")
////                deleteOrder(deal)
//                error.printStackTrace()
//            })
//        requestQueue.add(request)
    }

    private fun printOrder() {
        printing = true
        val dyzs = SPUtils[this, Constants.SP_DaYinZhangShu, 0] as Int

        //loading转圈圈
        val hud = KProgressHUD.create(this)
            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()

        AidlUtil.instance.printADeal(deal, dyzs, object : ICallback.Stub() {
            override fun onRunResult(isSuccess: Boolean) {
                hud.dismiss()
            }

            override fun onPrintResult(code: Int, msg: String?) {
                printing = false
                hud.dismiss()
                runOnUiThread {
                    if (code == 0) {//打印成功
                        ToastUtil.showToast(this@MainActivity, R.string.dayin_chenggong)
                        val dialog = QMUIDialog.MessageDialogBuilder(this@MainActivity)
                            .setMessage(getString(R.string.dingdanyidayin))
//                                .addAction("保留此单") { dialog, _ -> dialog.dismiss()}
                            .addAction(
                                R.string.confirm
                            ) { p0, _ ->
                                p0.dismiss()

                                allOrders = mutableListOf()
                                deletedOrders = mutableListOf()
                                todayOrders = mutableListOf()
                                todayBets = mutableListOf()
                                adapter.data.clear()
                                adapter.notifyDataSetChanged()
                                edtMoney.setText("")
                                edtNum.setText("")

                                belongTo.clear()
                                changeZone()
                                displayRegion()
                                edtMoney.requestFocus()//金额输入框获取焦点
                                showCount()

                                if (isModify) {
                                    setResult(RESULT_OK)
                                    finish()
                                }
                            }
                            .create()
                        dialog.setCancelable(true)
                        dialog.show()
                    } else {//打印失败
                        deleteOrder(deal)
                        val dialog = QMUIDialog.MessageDialogBuilder(this@MainActivity)
                            .setMessage(R.string.dayinshibai)
                            .addAction(
                                R.string.confirm
                            ) { p0, _ ->
                                p0.dismiss()
                            }
                            .create()
                        dialog.setCancelable(false)
                        dialog.show()
                    }
                }
            }

            override fun onReturnString(result: String?) {
            }

            override fun onRaiseException(code: Int, msg: String?) {
            }
        })
    }

    private fun deleteOrder(deal: Order) {
        //TODO 注释掉删订单的请求
//        val url = Constants.SERVER_URL + "deleteOrder"
//        val params = JSONObject()
//        params.put("serial_number", deal.serialNumber)

        RequestCenter.deleteOrderBySerialNumber(deal.serialNumber, object : OkHttpRequestCallback {
            override fun onSuccess(response: String?) {
                loadTodayOrders()
            }

            override fun onFailure(error: String?) {
                TLog.net("deleteOrderBySerialNumber() failure:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params,
//            {
//                val status = it.get("status") as Int
//                if (status == 200) {
////                    loadOrders()
//                    loadTodayOrders()
//
//                }
//            },
//            { error ->
//                error.printStackTrace()
//            })
//        requestQueue.add(request)
    }

    inner class MyAdapter(data: MutableList<BetCountEntity>) :
        BaseQuickAdapter<BetCountEntity, BaseViewHolder>(R.layout.item_bet, data) {
        override fun convert(helper: BaseViewHolder, item: BetCountEntity) {
            helper.setText(R.id.textMoney, item.money.toString())
                .setText(R.id.textNumber, item.getNumber())
                .setText(R.id.textPool, if (item.pool) "Pool" else "")
                .setText(
                    R.id.textBelong, deal.belongTo
                )
                .addOnClickListener(R.id.btnRemove)
//                    .addOnClickListener(R.id.textMoney)
        }
    }

    override fun onStart() {
        super.onStart()
        serverPing()
//        loadOrders()
//        loadTodayOrders()
    }

    override fun onStop() {
        super.onStop()
        if (timer != null) {
            timer.cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer.cancel()
        }
    }
}